ShapeApplet.java
ShapeApplet.java defines a simple applet that has buttons for the shapes Line, Rectangle, Circle, and Disc. If you click a button the corresponding shape appears in the applet's display region. ShapeApplet.java also defines an interface, Drawable, which is implemented in the abstract class, Shape. Shape is subclassed into Line, Rect, and Circle. Disc is derived from Circle. See Figure 5 for the class hierarchy.
import java.applet.*; import java.awt.*; interface Drawable { public void draw (Graphics graphics, Color color); } abstract class Shape implements Drawable { protected int width; protected int height; public void setSize (int w, int h) { width = w; height = h; } public void draw (Graphics graphics, Color color) { graphics.setColor (color); draw (graphics); } protected abstract void draw (Graphics graphics); } class Line extends Shape { protected void draw (Graphics graphics) { graphics.drawLine (0, 0, width, height); } } class Rect extends Shape { protected void draw (Graphics graphics) { graphics.drawRect (0, 0, width, height); } } class Circle extends Shape { protected int diameter () { int dia = (width > height) ? height : width; return dia; } protected void draw (Graphics graphics) { int dia = diameter (); graphics.drawOval (0, 0, dia, dia); } } class Disc extends Circle { protected void draw (Graphics graphics) { int dia = diameter (); // diameter used from Circle graphics.fillOval (0, 0, dia, dia); } } public class ShapeApplet extends Applet { public void init () { // create UI: provide 4 buttons setLayout(new BorderLayout()); // create a sub panel for containing buttons Panel buttons = new Panel(); add ("South",buttons); // create push buttons buttons.add (new Button ("Line")); buttons.add (new Button ("Rect")); buttons.add (new Button ("Circle")); buttons.add (new Button ("Disc")); } public boolean handleEvent (Event event) { boolean handled = false; if (event.id == Event.ACTION_EVENT) { handled = true; if ("Line".equals (event.arg)) { // draw a line Line l = new Line(); l.setSize (100, 80); l.draw (getGraphics(), Color.black); } else if ("Rect".equals (event.arg)) { // draw a Rectangle Rect r = new Rect(); r.setSize (100, 80); r.draw (getGraphics(), Color.blue); } else if ("Circle".equals (event.arg)) { // draw a Circle Circle c = new Circle(); c.setSize (100, 80); c.draw (getGraphics(), Color.red); } else if ("Disc".equals (event.arg)) { // draw a Disc Disc d = new Disc(); d.setSize (98, 78); d.draw (getGraphics(), Color.green); } } return handled; } }
BACK to Analyzing Java Programs with Cosmo Code